package org.youyun56.gpsserver.common;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class FileUtils {
    private static final String ENCODING_GBK = "GBK";

    public static boolean createFile(String filename) throws IOException {
        File file = new File(filename);
        boolean b = false;
        if (!file.exists()) {
            File parent = file.getParentFile();
            if (!parent.exists()) {
                parent.mkdirs();
            }
            b = file.createNewFile();
        }
        return b;
    }

    public static boolean deleteFile(String filename) {
        return new File(filename).delete();
    }

    public static void deleteDirectory(String filepath) throws IOException {
        File f = new File(filepath);
        if (f.exists() && f.isDirectory()) {
            if (f.listFiles().length == 0) {
                f.delete();
            } else {
                File[] delFile = f.listFiles();
                for (int index = 0; index < f.listFiles().length; index++) {
                    if (delFile[index].isDirectory()) {
                        deleteDirectory(delFile[index].getAbsolutePath());
                    }
                    delFile[index].delete();
                }
            }
            deleteDirectory(filepath);
        }
    }

    public static String loadContentFromRemoteURL(String urlAddress) throws FileNotFoundException, IOException {
        return loadContentFromRemoteURL(urlAddress, ENCODING_GBK);
    }

    public static String loadContentFromRemoteURL(String urlAddress, String encoding) throws IOException {
        String separator = System.getProperty("line.separator");
        StringBuilder builder = new StringBuilder();

        urlAddress = encodingPath(urlAddress);
        URL url = new URL(urlAddress);
        URLConnection conn = url.openConnection();
        InputStreamReader isr = new InputStreamReader(conn.getInputStream(), encoding);
        BufferedReader reader = new BufferedReader(isr);

        int index = 0;
        String line = null;
        while ((line = reader.readLine()) != null) {
            if (index++ > 0) {
                builder.append(separator);
            }
            builder.append(line);
        }
        reader.close();
        isr.close();

        return builder.toString();
    }

    public static List<String> loadFileLines(String file, String encoding) throws FileNotFoundException, IOException {
        return loadFileLines(file, encoding, 0, -1);
    }

    public static List<String> loadFileLines(String file, String encoding, int startLine, int size) throws FileNotFoundException, IOException {
        List<String> lines = new ArrayList<String>();
        InputStream is = new FileInputStream(file);
        InputStreamReader isr = new InputStreamReader(is, encoding);
        BufferedReader reader = new BufferedReader(isr);
        String line = null;
        int index = -1, count = 0;
        while ((line = reader.readLine()) != null) {
            index++;
            if (index < startLine) {
                continue;
            }
            lines.add(line);
            count++;
            if (size > 0 && count >= size) {
                break;
            }
        }
        reader.close();
        isr.close();
        is.close();
        return lines;
    }

    public static List<String> loadFileLines(String file) throws FileNotFoundException, IOException {
        return loadFileLines(file, ENCODING_GBK);
    }

    public static boolean writeFile(String file, String txt, boolean appent) throws IOException {
        File f = new File(file);
        if (!f.exists()) {
            createFile(file);
        }
        FileWriter writer = new FileWriter(f, appent);
        writer.write(txt);
        writer.close();
        return true;
    }

    public static boolean writeFile(String file, String txt, String encoding) throws IOException {
        File f = new File(file);
        if (!f.exists()) {
            createFile(file);
        }
        FileOutputStream fos = new FileOutputStream(file, true);
        OutputStreamWriter os = new OutputStreamWriter(fos, encoding == null ? "UTF-8" : encoding);
        os.write(txt);
        os.close();
        fos.close();
        return true;
    }

    public static String encodingPath(String url) throws UnsupportedEncodingException {
        if (url == null) {
            return null;
        }
        String regex = "[\\u4e00-\\u9fa5]+";
        Pattern pattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);
        Matcher matcher;

        StringBuilder buffer = new StringBuilder();
        int len = url.length();
        for (int i = 0; i < len; i++) {
            char chr = url.charAt(i);
            matcher = pattern.matcher(String.valueOf(chr));
            if (matcher.matches()) {
                buffer.append(java.net.URLEncoder.encode(String.valueOf(chr), "utf-8"));
            } else {
                buffer.append(chr);
            }
        }
        String string = buffer.toString().replace(" ", "%20");
        return string;
    }

    @Deprecated
    public static void writeObjectToFile(Object obj, String filename) throws IOException {
        FileUtils.deleteFile(filename);
        final FileOutputStream fos = new FileOutputStream(filename);
        ObjectOutputStream oos = new ObjectOutputStream(fos);
        oos.writeObject(obj);
        fos.close();
        oos.close();
    }

    @Deprecated
    public static Object readObjectFromFile(String filename) throws IOException, ClassNotFoundException {
        final FileInputStream fis = new FileInputStream(filename);
        ObjectInputStream ois = new ObjectInputStream(fis);
        Object obj = ois.readObject();
        fis.close();
        ois.close();
        return obj;
    }

}
